package cn.gjxblog.service.impl;

import cn.gjxblog.api.MailServiceFegin;
import cn.gjxblog.api.UserServiceFegin;
import cn.gjxblog.common.model.HttpResult;
import cn.gjxblog.common.model.PageCondition;
import cn.gjxblog.common.utils.UUIDUtils;
import cn.gjxblog.dao.*;
import cn.gjxblog.model.CommonConstants;
import cn.gjxblog.model.dto.HouseQueryDTO;
import cn.gjxblog.model.entity.*;
import cn.gjxblog.service.HouseService;
import cn.gjxblog.service.RecommendService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2018/12/12 16:09
 */
@Service
@Transactional
public class HouseServiceImpl implements HouseService {

    @Resource
    private HouseMapper houseMapper;

    @Resource
    private CityMapper cityMapper;

    @Resource
    private CommunityMapper communityMapper;

    @Resource
    private HouseUserMapper houseUserMapper;

    @Resource
    private HouseMsgMapper houseMsgMapper;

    @Resource
    private RecommendService recommendService;

    @Autowired
    private MailServiceFegin mailServiceFegin;

    @Autowired
    private UserServiceFegin userServiceFegin;

    @Override
    public PageInfo<House> searchHouses(HouseQueryDTO houseQueryDTO ) {
        PageCondition pageCondition = houseQueryDTO.getPageCondition();
        PageHelper.startPage(pageCondition.getPageNum(), pageCondition.getPageSize());
        HouseExample houseExample = new HouseExample();
        HouseExample.Criteria criteria = houseExample.createCriteria();

        House house = houseQueryDTO.getHouse();
        if(house != null){
            if(house.getId() != null){
                criteria.andIdEqualTo(house.getId());
            }
            if(house.getType() != null){
                criteria.andTypeEqualTo(house.getType());
            }
            if(house.getName()!= null){
                criteria.andNameLike("%"+house.getName()+"%");
            }
            if(house.getAddress()!=null){
                criteria.andAddressLike("%"+house.getAddress()+"%");
            }

        }

        if(pageCondition.getSort()!= null){
            if("price_asc".equals(pageCondition.getSort())){
                houseExample.setOrderByClause("price asc");
            }else if("price_desc".equals(pageCondition.getSort())){
                houseExample.setOrderByClause("price desc");
            }else if(StringUtils.equals("rating",pageCondition.getSort())) {
                houseExample.setOrderByClause("rating desc");
            }else{
                houseExample.setOrderByClause("create_time desc");
            }
        }
        List<House> houses = houseMapper.selectByExample(houseExample);

        PageInfo<House> housePageInfo = new PageInfo<>(houses);
        return housePageInfo;
    }



    @Override
    public House getHouse(String id) {
        HouseExample houseExample = new HouseExample();
        HouseExample.Criteria criteria = houseExample.createCriteria();
        criteria.andIdEqualTo(id);

        List<House> houses = houseMapper.selectByExample(houseExample);
        if(!houses.isEmpty()){
            return  houses.get(0);
        }
        return null;
    }

    @Override
    public List<Community> queryCommunitys() {
        List<Community> communities = communityMapper.selectByExample(new CommunityExample());
        return communities;
    }

    @Override
    public List<City> queryCitys() {
        List<City> cities = cityMapper.selectByExample(new CityExample());
        return cities;
    }

    @Override
    public void addHouse(House house, String userId) {
        house.setCreateTime(new Date());
        house.setId(UUIDUtils.get32LUUid());

        houseMapper.insertSelective(house);

        //维护关系
        addUser2House(house.getId(),userId,CommonConstants.SALE_STATE);


    }

    @Override
    public PageInfo<House> queryHousesByUserId(HouseQueryDTO houseQueryDTO) {
        PageCondition pageCondition = houseQueryDTO.getPageCondition();

        PageHelper.startPage(pageCondition.getPageNum(),pageCondition.getPageSize());

        HouseUserExample houseUserExample = new HouseUserExample();
        HouseUserExample.Criteria criteria = houseUserExample.createCriteria();

        criteria.andUserIdEqualTo(houseQueryDTO.getUserId());

        if(houseQueryDTO.isBookmarked()){
            criteria.andTypeEqualTo(CommonConstants.COLLECT_STATE);
        }else{
            criteria.andTypeEqualTo(CommonConstants.SALE_STATE);
        }

        List<HouseUser> houseUsers = this.houseUserMapper.selectByExample(houseUserExample);

        PageInfo<HouseUser> houseServicePageInfo = new PageInfo<>(houseUsers);
        List<House> houseList = houseUsers.stream()
                .map(houseUser -> getHouse(houseUser.getHouseId()))
                .collect(Collectors.toList());

        PageInfo<House> housePageInfo = new PageInfo<>(houseList);
        housePageInfo.setTotal(houseServicePageInfo.getTotal());
        return housePageInfo;
    }

    @Override
    public void addHouseMsg(HouseMsg houseMsg) {
        houseMsg.setId(UUIDUtils.get32LUUid());
        houseMsg.setCreateTime(new Date());

        houseMsgMapper.insertSelective(houseMsg);

        HttpResult<User> userResponseVO = userServiceFegin.getUserById(houseMsg.getAgentId());

        mailServiceFegin.snedSimplMail("来自用户" + houseMsg.getEmail(), houseMsg.getMsg(), userResponseVO.getResult().getEmail());
    }

    @Override
    public void updateRating(String id, Double rating) {
        Double oldRating = getHouse(id).getRating();
       Double newRating = oldRating.equals(0D) ? rating : Math.min(Math.round(oldRating + rating)/2, 5);
        House house = new House();
        house.setId(id);
        house.setRating(newRating);

        houseMapper.updateByPrimaryKeySelective(house);
    }

    @Override
    public void addUser2House(String id, String userId,Integer type) {
        //维护关系
        HouseUser houseUser = new HouseUser();
        houseUser.setId(UUIDUtils.get32LUUid());
        houseUser.setCreateTime(new Date());
        houseUser.setType(type);
        houseUser.setUserId(userId);
        houseUser.setHouseId(id);

        houseUserMapper.insert(houseUser);
    }

    @Override
    public void deleteUser2House(String houseId, String userId, Integer type) {
        HouseUserExample houseUserExample = new HouseUserExample();
        houseUserExample.createCriteria()
                .andHouseIdEqualTo(houseId)
                .andUserIdEqualTo(userId)
                .andTypeEqualTo(type);
        houseUserMapper.deleteByExample(houseUserExample);
    }

    @Override
    public void deleteHouse(String houseId) {
        //删除房屋信息
        houseMapper.deleteByPrimaryKey(houseId);

        //删除关系
        HouseUserExample houseUserExample = new HouseUserExample();
        houseUserExample.createCriteria().andHouseIdEqualTo(houseId);
        houseUserMapper.deleteByExample(houseUserExample);

        //删除排行榜数据
        recommendService.removeHouse(houseId);
    }
}
